<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>请求发送过程</title>
    <!-- <script src="../node_modules/axios/dist/mine-axios.js"></script> -->
</head>
<body>
<script type="text/javascript">
    // axios 发送请求
    // 声明构造函数
    function Axios(config) {
        this.config = config;
    }

    // 发送request
    Axios.prototype.request = function (config) {
        let p = Promise.resolve(config);
        console.log(p);
        // 声明一个数组
        let chain = [dispatchRequest, undefined]; // undefined 占位

        return p.then(chain[0], chain[1]);
    }

    // 2.dispatchRequest
    function dispatchRequest(config) {
        // 调用适配器发送请求
        return xhrAdapter(config).then((resp) => {
            // 对响应的结果进行转换处理
            return resp;
        }, (err) => {
            throw err;
        });
    }

    // 3.xhrAdapter
    function xhrAdapter(config) {
        console.log("xhrAdapter");
        return new Promise((resolve, reject) => {
            var xhr = new XMLHttpRequest();
            xhr.open(config.method, config.url);
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    if (xhr.status >= 200 && xhr.status < 300) {
                        resolve({
                            // 配置对象
                            config: config,
                            // 响应体
                            data: xhr.response,
                            // 响应头
                            headers: xhr.getAllResponseHeaders(),
                            // xhr请求对象
                            request: xhr,
                            // 响应状态码
                            status: xhr.status,
                            // 响应状态字符串
                            statusText: xhr.statusText
                        });
                    } else {
                        reject(new Error(`请求失败，失败的状态码为${xhr.status}`));
                    }
                }
            }
            xhr.send();
        });
    }

    // 4.创建axios函数
    let axios = Axios.prototype.request.bind(null);

    axios({
        method: 'GET',
        url: 'http://localhost:3000/posts'
    }).then(resp => {
        console.log(resp);
    });
</script>
</body>
</html>